import random
import string

from flask import Blueprint, render_template, jsonify,redirect,url_for,session
from exts import mail, db
from flask_mail import Message
from flask import request

from models import EmailCaptchaModel,UserModel

from .forms import RegisterForm,LoginForm

from werkzeug.security import generate_password_hash,check_password_hash

# 设置url前缀
# /auth
bp = Blueprint("auth", __name__, url_prefix="/auth")


@bp.route("/login", methods=['GET','POST'])
def login():
    if request.method == 'GET':
        return render_template("login.html")
    else:
        form = LoginForm(request.form)
        if form.validate():
            email = form.email.data
            password = form.password.data
            user = UserModel.query.filter_by(email=email).first()
            if not user:
                print("邮箱在数据库不存在")
                return redirect(url_for("auth.login"))
            if check_password_hash(user.password,password):
                # cookie中不适合存储太多数据，只适合存储少量数据，一般用来存储登录授权信息
                #flask中的session是经过加密存储在cookie中的
                session['user_id'] = user.id
                return redirect(url_for("qa.index"))
            else:
                print("密码错误")
                return redirect(url_for("auth.login"))
        else:
            print(form.errors)
            return redirect(url_for("auth.login"))


@bp.route("/logout")
def logout():
    session.clear()
    return redirect(url_for("qa.index"))


@bp.route("/register", methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template("register.html")
    else:
        # 表单验证 flask-wtf:wtforms
        # return render_template("register.html")
        form = RegisterForm(request.form)
        if form.validate():
            email = form.email.data
            username = form.username.data
            password = form.password.data
            user = UserModel(email=email,username=username,password=generate_password_hash(password))
            db.session.add(user)
            db.session.commit()
            # url_for获取视图函数对应的url
            return redirect(url_for("auth.login"))
        else:
            print(form.errors)
            return redirect(url_for("auth.register"))
    # return render_template("register.html")


# 如果没定method参数，默认是GET请求
@bp.route("/captcha/email")
def get_email_captcha():
    email = request.args.get("email")
    source = string.digits * 4
    captcha = random.sample(source, 4)
    captcha = "".join(captcha)
    # I/OSError操作
    message = Message(subject="知了传课注册验证码", recipients=[email], body=f"您的验证码是：{captcha}")
    mail.send(message)
    # memcached/redis <- 推荐使用，速度快功能强大
    # 用数据库方式存储
    email_captcha = EmailCaptchaModel(email=email, captcha=captcha)
    db.session.add(email_captcha)
    db.session.commit()

    # RESTful API
    # {code: 200/400/500, message:"",data:{}}
    return jsonify({"code": 200, "message": "", "data": None})

# @bp.route("/mail/test")
# def mail_test():
#     message = Message(subject="邮箱测试", recipients=["1075458839@qq.com"], body="这是一条测试邮件")
#     mail.send(message)
#     return "邮件发送成功！"
